package com.example.royalchef.utils;

import java.io.FileInputStream;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * 进行MD5加密工具类
 */
public class MD5Utils {

    /**
     * 对字符串进行加密
     *
     * @param password 需要加密的字符串
     * @return 经过MD5加密的字符串
     */
    public static String getStringMd5(String password) {
        StringBuffer sb = null;
        MessageDigest instance;
        try {
            // 获取MD5算法对象
            instance = MessageDigest.getInstance("MD5");
            // 对字符串加密，返回字节数组
            byte[] digest = instance.digest(password.getBytes());
            sb = new StringBuffer();
            for (byte b : digest) {
                // 获取字节的低八位有效字
                int i = b & 0xff;
                // 将整数转化为16进制
                String hexString = Integer.toHexString(i);
                if (hexString.length() < 2) {
                    // 如果是1位的话，补0
                    hexString = "0" + hexString;
                }
                sb.append(hexString);
            }
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return sb.toString();
    }

    /**
     * 获取文件的MD5值
     *
     * @param sourceDir 需要获取MD5的文件路径
     * @return 文件的MD5值
     */
    public static String getFileMd5(String sourceDir) {
        StringBuffer sb = null;
        MessageDigest instance;
        try {
            // 获取MD5算法对象
            instance = MessageDigest.getInstance("MD5");
            FileInputStream fis = new FileInputStream(sourceDir);
            byte[] buffer = new byte[1024];
            int len = 0;
            while ((len = fis.read(buffer)) != -1) {
                instance.update(buffer, 0, len);
            }
            byte[] digest = instance.digest();
            sb = new StringBuffer();
            for (byte b : digest) {
                // 获取字节的低八位有效字
                int i = b & 0xff;
                // 将整数转化为16进制
                String hexString = Integer.toHexString(i);
                if (hexString.length() < 2) {
                    // 如果是1位的话，补0
                    hexString = "0" + hexString;
                }
                sb.append(hexString);
            }
            return sb.toString();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}
